const crypto = require("crypto");

const ALGORITHM = "aes-256-ctr"; // 指定加密算法和模式
const SECRET_KEY = "VOVH6SDMPNWJRRIQCC7RDXS01LWHZFR3";
const IV = "1234567890123456"; // 16 字节 IV

/**
 * AES加解密类
 * @param {*} key 密钥，默认为 VOVH6SDMPNWJRRIQCC7RDXS01LWHZFR3，可选值：12345678
 * @param {*} iv 初始向量，默认为 16 字节 0 填充，可选值：1234567890123456
 * @param {*} algorithm 算法名，默认为 AES-256-ctr 即 AES 256 位CTR 模式，可选值：aes-128-cbc
 */
class AesSecurity {
	// 密钥
	key = SECRET_KEY;
	// 初始向量
	iv = IV;
	// 算法名
	algorithm = ALGORITHM;

	constructor(key, iv, algorithm) {
		if (key) this.key = Buffer.from(key, "utf8");
		if (iv) this.iv = Buffer.from(iv, "utf8");
		if (algorithm) this.algorithm = Buffer.from(algorithm, "utf8");
	}

	/**
	 * 加密
	 * @param {string} text
	 * @returns
	 */
	encrypt(text) {
		text = typeof text === "object" ? JSON.stringify(text) : text;
		// 压缩数据
		const cipher = crypto.createCipheriv(this.algorithm, this.key, this.iv);
		let encrypted = cipher.update(text, "utf8", "hex");
		encrypted += cipher.final("hex");
		return encrypted;
	}

	/**
	 * 解密
	 * @param {*} ciphertext
	 * @returns
	 */
	decrypt(encryptedText) {
		const decipher = crypto.createDecipheriv(this.algorithm, this.key, this.iv);
		let decrypted = decipher.update(encryptedText, "hex", "utf8");
		decrypted += decipher.final("utf8");
		return decrypted;
	}
}

module.exports = AesSecurity;
